#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import pathlib
from ..._util import Util, DynObject, CopiedAndSymlinkedDir
from ..._game import GameBase, GameSpec, MatchContext
from ..._game_straits import GameStraitForWindows, GameStraitNeedConfigDir


class PlantsVsZombies(GameBase, GameStraitForWindows):

    class UsersFileError(Exception):
        pass

    class UserFileError(Exception):
        pass

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedConfigDir())

        self._spec = GameSpec()
        if True:
            self._spec.windows_archs = [self.WindowsArch.WIN32]
            self._spec.windows_versions = [self.WindowsVersion.WINXP, "*"]

            self._spec.default_language = "en_US"
            self._spec.languages = [self._spec.default_language]

            # self._spec.resolutions = ["640x480", "800x600", "1024x768", "1280x1024", "1600x1200", "2048x1536"]
            self._spec.resolutions = ["640x480"]
            self._spec.can_fullscreen = True
            self._spec.can_windowed = True

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        # FIXME: should change name according to detected version
        return "Plants Vs Zombies"

    def _prepare(self, context):
        self._context = context
        try:
            self._openSaveFiles = set()

            self._targetGameDirObj = CopiedAndSymlinkedDir(os.path.join(self._context.drive_c_dirpath, "game"), [self._dataDir])
            self._targetGameDirObj.symlink("", recursive=True)
            self._targetGameDirObj.clear()

            self._archiveDir = _GameArchiveDir(self._context.drive_c_dirpath)
            self._archiveDir.import_archives(self._context.config_dirpath)

            self._reg = _GameRegistry(self._context.registry)
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._spec.default_language

    @MatchContext.edit_or_run
    def get_current_user(self):
        return self._reg.readCurUser()

    @MatchContext.edit_or_run
    def set_language(self, language):
        assert language == self._spec.default_language

    @MatchContext.edit_or_run
    def set_current_user(self, user):
        if user not in [x.name for x in _UsersFile.read(self._archiveDir.path)]:
            raise ValueError("user \"%s\" does not exists" % (user))
        return self._reg.writeCurUser(user)

    @MatchContext.edit
    def list_users(self):
        return [x.name for x in _UsersFile.read(self._archiveDir.path)]

    @MatchContext.edit
    def open_user_file(self, user):
        ret = _UsersFile.read(self._archiveDir.path)
        for i in range(0, len(ret)):
            if ret[i].name == user:
                return UserFile(self, self._archiveDir.path, user, ret[i].fileNumber)
        raise ValueError("user \"%s\" not found" % (user))

    @MatchContext.edit
    def delete_user_file(self, user):
        ret = _UsersFile.read(self._archiveDir.path)
        for i in range(0, len(ret)):
            if ret[i].name == user:
                assert ret[i].fileNumber not in self._openSaveFiles
                os.unlink(os.path.join(self._archiveDir.path, "user%d.dat" % (ret[i].fileNumber)))
                ret.pop(i)
                _UsersFile.write(self._archiveDir.path, ret)
                return
        raise ValueError("user \"%s\" not found" % (user))

    @MatchContext.run
    def apply_resolution(self, resolution):
        assert resolution in self._spec.resolutions

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        self._reg.writeFullscreenOrWindowed(fullscreen_or_windowed)

    def _commit(self):
        pass

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        # this game can't find resource files if cwd is not specified
        return self.RunInfo("C:\\game\\PlantsVsZombies.exe", cwd="C:\\game")

    def _cleanup(self, on_error=False):
        if hasattr(self, "_archiveDir"):
            if not on_error:
                self._archiveDir.export_archives(self._context.config_dirpath)
            del self._archiveDir
        if hasattr(self, "_reg"):
            del self._reg
        if hasattr(self, "_targetGameDirObj"):
            if not on_error:
                pass
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context


class UserFile:

    # https://plantsvszombies.fandom.com/wiki/User_file_format

    def __init__(self, parent, archiveDir, name, fileNumber):
        assert fileNumber not in parent._openSaveFiles

        self._parent = parent

        self._archiveDir = archiveDir
        self._name = name
        self._fileNumber = fileNumber
        self._path = os.path.join(self._archiveDir, "user%d.dat" % (self._fileNumber))

        self._buf = pathlib.Path(self._path).read_bytes()
        self._bChanged = False

        self._parent._openSaveFiles.add(self._fileNumber)

    @property
    def path(self):
        return self._path

    @property
    def changed(self):
        return self._bChanged

    def clone_as(self, user):
        ret = _UsersFile.read(self._archiveDir)

        if user in [x.name for x in ret]:
            raise ValueError("user \"%s\" already exists" % (user))

        # FIXME
        assert False

    def get_name(self):
        return self._name

    def get_money(self):
        return int.from_bytes(self._buf[0x008:0x00C], byteorder="little") * 10

    def set_name(self, name):
        if len(name) > 8:
            raise ValueError("user name must be less than 8 characters")

        ret = _UsersFile.read(self._archiveDir)

        if name in [x.name for x in ret]:
            raise ValueError("user name \"%s\" already exists" % (name))

        for i in range(0, len(ret)):
            if ret[i].name == self._name:
                ret[i].name = name
                _UsersFile.write(self._archiveDir, ret)
                break

        self._name = name
        self._bChanged = True

    def set_money(self, money):
        if not (0 <= money <= 999990):
            raise ValueError("money must be in the range of 0 to 999,990")
        if money % 10 != 0:
            raise ValueError("money must be divisible by 10")

        # self._buf[0x008:0x00C] is money
        self._buf = self._buf[:0x008] + (money // 10).to_bytes(4, byteorder="little") + self._buf[0x00C:]
        self._bChanged = True

    def save(self):
        if not self._bChanged:
            return

        pathlib.Path(self._path).write_bytes(self._buf)
        self._bChanged = False

    def close(self):
        self._parent._openSaveFiles.remove(self._fileNumber)
        del self._bChanged
        del self._buf
        del self._fileNumber
        del self._name
        del self._path
        del self._archiveDir
        del self._parent

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()


class _GameArchiveDir:

    def __init__(self, drive_c_dirpath):
        self._tDir = os.path.join(drive_c_dirpath, "ProgramData", "PopCap Games", "PlantsVsZombies", "userdata")

    @property
    def path(self):
        return self._tDir

    def import_archives(self, backup_archive_dir):
        srcDir = os.path.join(backup_archive_dir, "userdata")
        if os.path.isdir(srcDir):
            Util.forceCopy(srcDir, self._tDir)
        else:
            Util.forceDelete(self._tDir)

    def export_archives(self, backup_archive_dir):
        dstDir = os.path.join(backup_archive_dir, "userdata")
        if os.path.isdir(self._tDir):
            Util.forceCopy(self._tDir, dstDir)
        else:
            Util.forceDelete(dstDir)


class _UsersFile:

    # https://github.com/chiaracoetzee/plants-vs-zombies-user-file-editor/blob/master/Plants%20vs.%20Zombies%20user%20file%20editor/FormSelectUser.cs

    @classmethod
    def read(cls, archiveDir):
        ret = []
        try:
            with open(cls._path(archiveDir), "rb") as f:
                if f.read(4) != b'\x0E\x00\x00\x00':
                    raise PlantsVsZombies.ParseError("incompatible data format version")
                numUsers = int.from_bytes(f.read(2), byteorder="little")
                for i in range(0, numUsers):
                    nameLen = int.from_bytes(f.read(2), byteorder="little")
                    obj = DynObject()
                    obj.name = f.read(nameLen).decode("iso8859-1")
                    obj.timestamp = int.from_bytes(f.read(4), byteorder="little")
                    obj.fileNumber = int.from_bytes(f.read(4), byteorder="little")
                    ret.append(obj)
        except FileNotFoundError:
            pass
        return ret

    @classmethod
    def write(cls, archiveDir, data):
        # FIXME
        assert False

    @staticmethod
    def _path(archiveDir):
        return os.path.join(archiveDir, "users.dat")


class _GameRegistry:

    _keyName = "HKEY_CURRENT_USER\\Software\\PopCap\\PlantsVsZombies"

    def __init__(self, regObj):
        self._regObj = regObj

    def readCurUser(self):
        return self._regObj.get_value(self._keyName, "CurUser", value_type="REG_SZ", fallback_value="")

    def writeCurUser(self, value):
        # FIXME: check value
        self._regObj.add_value(self._keyName, "CurUser", "REG_SZ", value)

    def readFullscreenOrWindowed(self):
        return self._regObj.get_value(self._keyName, "ScreenMode", value_type="REG_DWORD", fallback_value=1)    # 1 means fullscreen

    def writeFullscreenOrWindowed(self, value):
        self._regObj.add_value(self._keyName, "ScreenMode", "REG_DWORD", 1 if value else 0)
